package org.linlinjava.litemall.core.storage;

import io.minio.MinioClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;

import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.file.Path;
import java.util.stream.Stream;

/**
 * @author Destin
 * @date 2018/7/16 16:10
 * @decrpt 阿里云对象存储服务
 */
public class MinioStorage implements Storage {

    private static Logger logger = LoggerFactory.getLogger(MinioStorage.class);

    private String bucketName;

    private String endpoint;


    private MinioClient minioClient;

    private static final String DEFAULT_CHARSET = "UTF-8";

    public MinioStorage(String bucketName, String endpoint, MinioClient minioClient) {
        this.bucketName = bucketName;
        this.endpoint = endpoint;
        this.minioClient = minioClient;
    }

    private String getBaseUrl() {
        return endpoint + "/" + bucketName + "/";
    }

    @Override
    public void store(InputStream inputStream, long contentLength, String contentType, String keyName) {
        try {
            minioClient.putObject(bucketName, keyName, inputStream, contentType);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public Stream<Path> loadAll() {
        return null;
    }

    @Override
    public Path load(String keyName) {
        return null;
    }

    @Override
    public Resource loadAsResource(String keyName) {
        try {
            URL url = new URL(getBaseUrl() + keyName);
            Resource resource = new UrlResource(url);
            if (resource.exists() || resource.isReadable()) {
                return resource;
            } else {
                return null;
            }
        } catch (MalformedURLException e) {
            logger.error(e.getMessage(), e);
            return null;
        }
    }

    @Override
    public void delete(String keyName) {
        try {
            minioClient.removeObject(bucketName, keyName);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public String generateUrl(String keyName) {
        return getBaseUrl() + keyName;
    }
}
